import { ElMessage } from 'element-plus'
import { Base64 } from 'js-base64';
export default function () {
	let api = inject('api');

    //获取七牛云文件命名
    function getQnKey(state){
		let prefix = localStorage.getItem('prefix')
		let _date = new Date();
		let y = _date.getFullYear()+'';
		let m = _date.getMonth()+1;
		let d = _date.getDate()<10?'0'+_date.getDate():_date.getDate();
		let name = prefix+'/'+y+m+d+_date.getTime()+Math.ceil(Math.random()*100);
		if(state)upQiniu.key=name
		return name;
	}

    //七牛云上传配置
    const upQiniu = reactive({
        token:'',
        key:getQnKey(),
    });

    //获取七牛云Token
	const getQnToken = async ()=>{
		let token = localStorage.getItem('qiNiuToken');
		if(token){
			upQiniu.token = token;
		}else{
			// let res = await api.post("a/other/getQiNiuToken",{name:'other'})
			// upQiniu.token = res.data;
			// localStorage.setItem('qiNiuToken',upQiniu.token)
		}
	} 
	
	getQnToken()

	//图片上传之前
	const imgFun = (file)=>{

		//获取文件后缀
		let index= file.type.lastIndexOf("/");
		let type = file.type.substring(index+1,file.type.length);
		
		upQiniu.key = getQnKey()+'.'+type;
		
		console.log(upQiniu.key,888888)
		
		const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'|| file.type === 'image/webp'
        const isLt1M = file.size / 1024 / 1024 < 1
        if (!isJPG) {
			ElMessage.error('文件只能是 jpeg、png、gif 格式!')
			return false;
        }
        if (!isLt1M) {
			ElMessage.error('上传图片大小不能超过 1MB!')
			return false;
        }
        return isJPG && isLt1M
	}
	
	//上传base64文件到七牛云
	const upFile = (prefix,base64,fn)=>{
		let token = localStorage.getItem('qiNiuToken');
		var pic = base64.split("base64,")[1];
		var key = getQnKey()+'.jpg';
		var url = "http://upload-z2.qiniup.com/putb64/-1/key/"+Base64.encode(key); 
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange=function(){
			if (xhr.readyState==4){
			  console.log(xhr)
			  console.log(JSON.parse(xhr.responseText))
			  api.post("api/Img/up_data",{
			  	prefix,
			  	key:JSON.parse(xhr.responseText).key,
			  })
			  fn(JSON.parse(xhr.responseText))
			}
		}
		xhr.open("POST", url, true);
		xhr.setRequestHeader("Content-Type", "application/octet-stream");
		xhr.setRequestHeader("Authorization", 'UpToken ' + token);
		xhr.send(pic);
	}
	
	//删除文件
	const delQnImg = (v) => {
		api.post("api/Img/del_data",{id:v.id})
		return api.post("a/other/delQiniuFile", {
			key: v.key,
			space:'other'
		})
	}
    return {upQiniu,imgFun,getQnToken,delQnImg,getQnKey,upFile};
}